using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using System.Collections.Generic;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class UIN_LevelHeroHeadList : UIBaseNode
    {
        #region Template Generate,don't modify

        protected class UIB_UIN_LevelHeroHeadList
        {
            #region ObjectBinding Generate

            public GameObject hero { protected set; get; }

            public virtual void InitBinding(ObjectBinding __binding)
            {
                __binding.TryGetVariableValue<GameObject>("hero", out var __tbv0);
                hero = __tbv0;
            }

            #endregion ObjectBinding Generate
        }

        #endregion Template Generate,don't modify


        protected UIB_UIN_LevelHeroHeadList ui { get; set; }
        private UIMsgDispatcher currMsgDispatcher => this._msgDispatcher as UIMsgDispatcher;

        #region Field

        private readonly List<DynLevelHero> _heroDataList = new();
        private ListScrollAdapter<UIN_LevelHeroHead> _headHeads;

        #endregion

        #region Override

        protected override void BeforeInit()
        {
            ui = new UIB_UIN_LevelHeroHeadList();
            ui.InitBinding(csObjBind);
        }

        protected override void OnInit()
        {
            _headHeads = InitListScroll<UIN_LevelHeroHead>(ui.hero, RefreshHeroHead);
            _headHeads.RefillCells(_heroDataList.Count);
        }

        protected override void OnShow()
        {

        }

        protected override void OnHide()
        {

        }
        public void Refresh()
        {
            UpdateHeroData();
            _headHeads.RefillCells(_heroDataList.Count);
        }

        private void UpdateHeroData()
        {
            var heroDataList = LevelPlayUtil.GetDynLevelPlayer().levelHeros;
            _heroDataList.Clear();
            foreach (var heroData in heroDataList)
            {
                _heroDataList.Add(heroData);
            }
        }

        protected override void AddMsgListeners()
        {
            currMsgDispatcher.AddListener(MsgEventType.Level_UpdateHeroHpSp, OnLevelUpdateHeroHpSp);
        }

        protected override void OnDispose()
        {

        }
        #endregion

        #region Method

        private void OnLevelUpdateHeroHpSp()
        {
            UpdateHeroData();
            _headHeads.RefillCells(_heroDataList.Count);
        }

        private void RefreshHeroHead(UIN_LevelHeroHead heroHead, int index)
        {
            var heroData = _heroDataList[index];
            if (heroData == null) return;
            heroHead.Show();
            heroHead.Refresh(heroData);
        }

        #endregion
    }
}
